package com.aliyun.openservices.springboot.example.normal;

import com.aliyun.openservices.ons.api.*;
import com.aliyun.openservices.springboot.example.config.MqConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Properties;
//效果和 DemoMessageListener 一致
//(使用了别人的代码，打算有点问题，改造了下)
//@Component
public class RocketMQConsumer {
 
    @Autowired
    private MqConfig rocketMQConfig;
 
 
    /**
     * 1、普通订阅
     *
     * @param
     */
    @Bean //不加@Bean Spring启动时没有注册该方法，就无法被调用
    public void normalSubscribe( ) {
 
        Properties properties = rocketMQConfig.getMqPropertie();
 
        properties.put(PropertyKeyConst.GROUP_ID,rocketMQConfig.getGroupId());
 
        Consumer consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe(rocketMQConfig.getTopic(), rocketMQConfig.getTag(), new MessageListener() {
            @Override
            public Action consume(Message message, ConsumeContext context) {
                System.out.println("Receive: " + new String(message.getBody()));
 
                //把消息转化为java对象
                //JSONObject jsonObject=JSONObject.parseObject(jsonString);
                //Book book= jsonObject.toJavaObject(Book.class);

                return Action.CommitMessage;
            }
        });
 
        consumer.start();
    }
}